package com.ants.project.core.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * 二维码生成器
 * 生成web链接二维码
 * 生成本地二维码图片
 * Created by liushun on 2016/6/30.
 */
public class QRCodeUtil {

    private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 生成文件二维码
     * @param matrix
     * @param fileName
     */
    public static void writeToFile(BitMatrix matrix, String fileName) {
        BufferedImage image = toBufferedImage(matrix);
        try {
            File file = new File(fileName);
            ImageIO.write(image, "png", file);
        } catch (IOException e) {
            logger.error("生成文件二维码异常!", e.getMessage());
        }
    }

    /**
     * 生成图片流二维码
     * @param matrix
     * @param format
     * @param stream
     */
    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) {
        BufferedImage image = toBufferedImage(matrix);
        try{
            ImageIO.write(image, format, stream);
        } catch (IOException e) {
            logger.error("Could not write an image of format "+ e.getMessage());
        }
    }

    /**
     * 设置二维码属性
     * @param width 二维码宽度
     * @param height 二维码高度
     * @param content 二维码内容
     * @return
     */
    public static BitMatrix setBitMatrix(int width, int height, String content){

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");	// 内容所使用字符集编码

        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return bitMatrix;
    }

    public static void main(String[] args) {

        // 生成二维码
        for(int i=0;i<5;i++)
            QRCodeUtil.writeToFile(setBitMatrix(500, 500, "测试"), "e:/code_"+i+".jpg");
    }
}
